package com.lv.suyiyong.hfr.ui

import android.graphics.Typeface
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SizeUtils
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.lv.common.adapter.FactoryContainerPagerAdapter
import com.lv.common.base.BaseActivity
import com.lv.common.bean.CommonSelectedBean
import com.lv.common.ktx.AppBarState
import com.lv.common.ktx.LoadSrc
import com.lv.common.ktx.setSelectedTabIndicatorFixWidth
import com.lv.common.ktx.setupAppBarLayoutListener
import com.lv.common.ktx.viewLifeCycleOwner
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.YgxUtilsKt
import com.lv.common.utils.showToast
import com.lv.service.bean.GoodsBean
import com.lv.service.bean.GoodsItemBean
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.room.category.SpuCategoryBean
import com.lv.service.room.category.SpuCategoryDbHelper
import com.lv.service.utils.YgxToolsKt
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.adapter.BannerHotSalerGoodsAdapter
import com.lv.suyiyong.hfr.databinding.ActivityHotSalerTabBinding
import com.lv.suyiyong.hfr.fragment.HotSalerGoodsFragment
import com.youth.banner.listener.OnBannerListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.androidx.viewmodel.ext.android.viewModel
import kotlin.math.abs

/**
 * 作者： ygx
 * 创建日期：2023/3/28 5:51 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：热销 页面
 */
@Route(path = ARoutUtils.HotSalerTabActivity)
class HotSalerTabActivity : BaseActivity<ActivityHotSalerTabBinding>() {
    private val mBannerTopData = mutableListOf<List<GoodsItemBean>>()

    private var mBannerTopAdapter: BannerHotSalerGoodsAdapter? = null
    private val mTopIv =
        "https://suyiyong.oss-cn-hangzhou.aliyuncs.com/iOS/projectPic/hfr/hotSaleNav.png"
    private var mUserInfo: UserInfo? = null
    private val mTabs = mutableListOf<CommonSelectedBean>()
    private var mAdapter: FactoryContainerPagerAdapter? = null

    private val serviceViewModel: ServiceViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    override fun getLayoutRes() = R.layout.activity_hot_saler_tab
    override fun initView() {
        super.initView()
        initStatusBar(this, true, false)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@HotSalerTabActivity, viewStatus)
            ivBackPage.setOnClickListener { finish() }
        }
    }


    override fun initConfig() {
        super.initConfig()
        mBinding.ivTitlePage.LoadSrc(mTopIv)
        initBannerAdapter()
        bannerObserver()
        lifecycleScope.launch {
            val taskCategory = async {
                val mAllCategory = getCategoryForDB()
                mTabs.clear()
                mTabs.add(CommonSelectedBean("推荐", postiont = 0, selected = true))
                mAllCategory?.forEach {
                    mTabs.add(CommonSelectedBean(it.name, postiont = it.fcaid))
                }
            }
            taskCategory.await()
            initPage()
        }

        UserDbHelper.getLiveUserInfo(this).observeKt {
            mUserInfo = it
        }
    }

    private suspend fun getCategoryForDB(): List<SpuCategoryBean>? {
        return withContext(Dispatchers.IO) {
            //获取工厂分类
            SpuCategoryDbHelper.getFindAllCategorySuspend(this@HotSalerTabActivity)
        }
    }

    private fun salehotTop() {
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { serviceViewModel.salehotTop() }.await()
            parseBannerResult(result)
        }
    }

    private fun parseBannerResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<GoodsBean> { code, data, message, result ->
                LogUtils.e("aaa")
                val items = data?.items
                mBannerTopData.clear()
                val chunked = items?.chunked(3)
                chunked?.let { mBannerTopData.addAll(it) }
                mBannerTopAdapter?.notifyDataSetChanged()
//                val startup = YgxUtilsKt.parseBannerTime(mBannerTopData[0].startup)
//                mBinding.bannerAv.setLoopTime(startup)
            }
            onBizError<String> { code, message, data ->
                showToast(message)
            }
        }
    }

    /**
     * 设置Banner适配器
     */
    private fun bannerObserver() {
        mBinding.bannerTop.addBannerLifecycleObserver(viewLifeCycleOwner)
            .setAdapter(mBannerTopAdapter)
            .setIntercept(false)

    }

    /**
     * 初始化轮播图Adapter
     */
    private fun initBannerAdapter() {
        mBannerTopAdapter = BannerHotSalerGoodsAdapter(mBannerTopData)

        mBannerTopAdapter?.setOnBannerListener(OnBannerListener<Any?> { data, position ->
//            val indexCommon = mBannerTopData[position]
//            YgxSYYADKt.arout2page(
//                this,
//                indexCommon.tag,
//                indexCommon.url,
//                mUserInfo,
//                adId = if (indexCommon.statistics == 0) indexCommon.id else -1
//            )
//            mBannerTopData[position].statistics = -1
        })
    }


    override fun initEvents() {
        super.initEvents()
        mBinding.appBar.setupAppBarLayoutListener { state ->
            when (state) {
                AppBarState.EXPANDED -> {
                    // 展开状态，比如显示 FAB 或设置标题
                    mBinding.tabLayout.setBackgroundResource(com.lv.common.R.drawable.bg_half_t_white_10)
                }

                AppBarState.COLLAPSED -> {
                    // 折叠状态
                    mBinding.tabLayout.setBackgroundResource(com.lv.common.R.drawable.bg_cir_white)
                }

                AppBarState.PARTIALLY_COLLAPSED -> {
                    // 中间状态
                    mBinding.tabLayout.setBackgroundResource(com.lv.common.R.drawable.bg_half_t_white_10)
                }
            }

        }
        val threshold = SizeUtils.dp2px(180.0f)
        mBinding.appBar.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, verticalOffset ->
            val abs = abs(verticalOffset)
            var mAlpha: Float = abs * 1.0f / threshold
            if (mAlpha < 0) {
                mAlpha = 0.0f
            }
            if (mAlpha > 1) {
                mAlpha = 1.0f
            }
            mBinding.viewStatus.alpha = mAlpha
        })


    }

    override fun initData() {
        super.initData()

    }

    private fun initPage() {
        salehotTop()
        initViewPager()
    }


    private fun initViewPager() {

        mAdapter = FactoryContainerPagerAdapter(
            supportFragmentManager, lifecycle,
            mTabs
        )
        mAdapter?.listener = object : FactoryContainerPagerAdapter.CirTabListener {
            override fun getFragment(position: Int): Fragment {
                val fragment = HotSalerGoodsFragment.newInstance(mTabs[position].postiont)
                return fragment
            }
        }

        mBinding.viewpager.adapter = mAdapter
        TabLayoutMediator(mBinding.tabLayout, mBinding.viewpager) { tab, position ->
            tab.text = mTabs[position].name
        }.attach()
        mBinding.viewpager.offscreenPageLimit = mTabs.size
        mBinding.tabLayout.setSelectedTabIndicatorFixWidth(SizeUtils.dp2px(19.0f).toFloat())
        mBinding.tabLayout.addOnTabSelectedListener(YgxToolsKt.setSelectedBoldTab())

        val selecTab = mTabs[0].name ?: ""
        val spannedString = YgxToolsKt.setTextSpan(selecTab, Typeface.BOLD)
        mBinding.tabLayout.getTabAt(0)?.text = spannedString
    }


}